package com.panopset;

import static com.panopset.Util.*;

import com.panopset.security.Encrypter;

/**
 * This is an ASCII text scrambler. Some applications, such as email, don't
 * function very well with binary level encryption.
 *
 * @author Karl Dinwiddie
 *
 */
public class TextScrambler {

    private TextScrambler(String password) {
        this.pwd = password;
    }

    /**
     * Scramble a message.
     *
     * @param msg
     * @param pwd
     * @return
     */
    public static String scramble(String msg, String pwd) {
        return s(msg, pwd, true);
    }

    /**
     * Unscramble a message.
     *
     * @param msg
     * @param pwd
     * @return
     */
    public static String unscramble(String msg, String pwd) {
        return s(msg, pwd, false);
    }

    private final String pwd;

    private static final String NO_MESSAGE = x("No plain text message supplied.");
    private static final String NO_PASSWORD = x("Please select a password.");
    private static final String PASSWORD_TO_SHORT = x("Password should be at least 4 characters long.");

    private static String s(String msg, String pwd, boolean b) {

        if (msg == null) {
            Alert.yellow(NO_MESSAGE);
            return "";
        }

        if (msg.length() < 1) {
            Alert.yellow(NO_MESSAGE);
            return "";
        }

        if (pwd == null) {
            Alert.red(NO_PASSWORD);
            return "";
        }

        if (pwd.length() < 4) {
            Alert.red(PASSWORD_TO_SHORT);
            return "";
        }

        dspmsg("");

        try {
            if (b) {
                Alert.yellow(x("scrambling..."));
            } else {
                Alert.yellow(x("unscrambling..."));
            }
            String rtn = new TextScrambler(pwd).morph(msg, b);
            Alert.clearYellow();
            if (b) {
                Alert.green(x("Scramble complete."));
            } else {
                Alert.green(x("Unscramble complete."));
            }
            return rtn;
        } catch (Exception e) {
            log(e);
            Alert.red(x("See log, most errors due to incorrect password."));
            return "";
        }
    }

    private String morph(String msg, boolean b) throws Exception {
        Encrypter encrypter = new Encrypter(pwd, 80);
        return b ? encrypter.encrypt(msg) : encrypter.decrypt(msg);
    }
}
